//
//  NSDate+YSAdd.m
//  YSiReader
//
//  Created by MOLBASE on 2017/10/23.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "NSDate+YSAdd.h"

static NSString *const kDefaultDateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";

@implementation NSDateFormatter (YSAdd)
+ (instancetype)sharedDateFormatter {
    static NSDateFormatter *_df = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _df = [[NSDateFormatter alloc] init];
        [_df setLocale:[NSLocale currentLocale]];
        [_df setDateFormat:kDefaultDateFormat];
    });
    return _df;
}
@end

@implementation NSDate (YSAdd)

- (NSString *)ys_time {
    NSDateFormatter *formatter = [NSDateFormatter sharedDateFormatter];
    formatter.dateFormat = @"HH:mm";
    return [formatter stringFromDate:self];
}

+ (NSString *)ys_currentTime {
    return [[NSDate date] ys_time];
}

+ (NSDate *)ys_dateWithString:(NSString *)dateString {
    NSDateFormatter *formatter = [NSDateFormatter sharedDateFormatter];
    return [formatter dateFromString:dateString];
}

+ (NSDate *)ys_dateWithString:(NSString *)dateString format:(NSString *)format {
    NSDateFormatter *formatter = [NSDateFormatter sharedDateFormatter];
    if(format) [formatter setDateFormat:format];
    return [formatter dateFromString:dateString];
}

- (NSString *)ys_getUpdateString {
    NSInteger intevalTime = [[NSDate date] timeIntervalSinceDate:self];
    
    // 分、时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours   = intevalTime / 60 / 60;
    NSInteger day     = intevalTime / 60 / 60 / 24;
    NSInteger month   = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers    = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10) {
        return  @"刚刚";
    }else if (minutes < 60){
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }else if (hours < 24){
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30){
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"M月d日";
        NSString * time = [df stringFromDate:self];
        return time;
    }else if (yers >= 1){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"yyyy年M月d日";
        NSString * time = [df stringFromDate:self];
        return time;
    }
    return @"";
}

@end
